// topic-challenge.js - 主题挑战页面的核心逻辑
const app = getApp();
// 引入音频工具
const audioUtils = require('../../../utils/audioUtils');
// 初始化数据管理器
const challengeDataManager = app.getChallengeDataManager();

Page({
  data: {
    // 挑战配置
    maxHints: 3,
    hintsUsed: 0,
    coinsPerCorrect: 15,
    bonusForWin: 30,
    passingScore: 60,
    
    // 发音相关状态
    isPlaying: false,
    
    // 挑战状态
    isLoading: true,
    isChallengeCompleted: false,
    isWin: false,
    isOptionSelected: false,
    isCorrect: false,
    isScoreChanging: false,
    
    // 题目数据
    topic: '',
    topicName: '',
    questions: [],
    currentQuestionIndex: 0,
    currentQuestion: {},
    selectedOption: -1,
    correctAnswerIndex: -1,
    totalQuestions: 0,
    progressPercentage: 0,
    hintAnimation: -1,
    
    // 得分数据
    currentScore: 0,
    finalScore: 0,
    coinsEarned: 0,
    finalCoins: 0,
    correctAnswers: 0,
    accuracy: 0,
    
    // 结果信息
    resultMessage: '',
    
    // 辅助变量
    isLastQuestion: false
  },

  onLoad: function(options) {
    // 获取全局应用实例和工具类
    this.app = getApp();
    this.magicCoinManager = this.app.getMagicCoinManager();
    
    // 从路由参数获取主题信息
    if (options.topic) {
      this.setData({
        topic: options.topic
      });
    }
    
    if (options.topicName) {
      this.setData({
        topicName: decodeURIComponent(options.topicName)
      });
    }
    
    // 获取全局应用实例
    this.app = getApp();
    
    // 初始化音频管理器
    this.initAudioManager();
    
    // 初始化挑战
    this.initChallenge();
  },
  
  // 初始化音频管理器
  initAudioManager: function() {
    if (!this.audioManager) {
      try {
        // 获取全局AudioManager实例
        this.audioManager = this.app.getAudioManager();
        this.audioManager.addStatusChangeCallback(this.onAudioStatusChange.bind(this));
      } catch (error) {
        console.warn('音频管理器加载失败:', error);
      }
    }
  },
  
  // 音频状态变化回调函数
  onAudioStatusChange: function(status) {
    this.setData({
      isPlaying: status.isPlaying
    });
  },
  
  onUnload: function() {
    // 移除音频状态变化回调
    if (this.audioManager) {
      this.audioManager.removeStatusChangeCallback(this.onAudioStatusChange.bind(this));
    }
  },

  // 初始化挑战
  initChallenge: function() {
    this.setData({
      isLoading: true,
      isChallengeCompleted: false,
      hintsUsed: 0,
      currentScore: 0,
      coinsEarned: 0,
      correctAnswers: 0,
      currentQuestionIndex: 0,
      progressPercentage: 0,
      isLastQuestion: false,
      hintAnimation: -1
    });
    
    // 生成主题相关的题目
    this.generateTopicQuestions();
    
    this.setData({
      isLoading: false
    });
  },

  // 生成主题相关的题目
  generateTopicQuestions: function() {
    // 根据主题获取单词数据
    const topicWords = this.getWordsByTopic(this.data.topic);
    
    // 如果没有单词数据（没有词书），提示并返回上一页
    if (topicWords.length === 0) {
       wx.showToast({
        title: '请先选择词书',
        icon: 'none'
      });
      // 返回上一页
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
      return;
    }
    
    // 生成题目
    const questions = [];
    
    // 为每个单词生成不同类型的题目
    topicWords.forEach((word, index) => {
      // 随机选择题目类型
      const questionTypes = ['definition', 'image', 'audio'];
      const randomType = questionTypes[Math.floor(Math.random() * questionTypes.length)];
      
      // 生成错误选项
      const incorrectOptions = this.generateIncorrectOptions(word.definition, topicWords);
      
      // 创建选项数组
      const options = [...incorrectOptions, word.definition];
      
      // 打乱选项顺序
      const shuffledOptions = options.sort(() => Math.random() - 0.5);
      
      // 找到正确答案的索引
      const correctIndex = shuffledOptions.indexOf(word.definition);
      
      // 处理pronunciation对象，提取具体的音标字符串
      let phoneticText = '';
      if (word.pronunciation) {
        // 优先使用美式音标，如果没有则使用英式音标
        if (word.pronunciation.us) {
          phoneticText = word.pronunciation.us;
        } else if (word.pronunciation.uk) {
          phoneticText = word.pronunciation.uk;
        }
      }

      // 创建题目对象
      let question = {
        id: `q-${index}`,
        type: randomType,
        word: word.word,
        phonetic: phoneticText,
        definition: word.definition,
        options: shuffledOptions,
        correctAnswerIndex: correctIndex,
        pronunciation: word.pronunciation
      };
      
      // 根据题目类型添加不同的属性
      switch(randomType) {
        case 'definition':
          question.prompt = '请选择正确的中文释义';
          break;
        case 'image':
          question.prompt = '请选择图片中物品的英文单词';
          // 优先使用单词对象中的实际图片，如果没有则使用占位符
          // 处理images可能是数组的情况，取第一个图片URL
          let imageUrl = '/images/book.png'; // 默认占位符
          if (word.images) {
            if (Array.isArray(word.images) && word.images.length > 0) {
              imageUrl = word.images[0]?.image;
            }
          }
          question.imageUrl = imageUrl;
          break;
        case 'audio':
          question.prompt = '请选择听到的单词';
          // 由于没有实际音频，使用占位符
          question.audioUrl = '';
          break;
      }
      
      questions.push(question);
    });
    
    this.setData({
      questions: questions,
      totalQuestions: questions.length,
      currentQuestion: questions[0],
      correctAnswerIndex: questions[0].correctAnswerIndex,
      progressPercentage: 0
    });
  },

  // 根据主题获取单词数据
  getWordsByTopic: function(topic) {
    // 使用wordDataManager从实际数据存储中获取分类单词
    const wordsByCategory = wordDataManager.getWordsByCategory(topic) || [];
    
    // 如果没有找到对应分类的单词，默认返回动物分类
    if (wordsByCategory.length === 0 && topic !== 'animal') {
      return this.getWordsByTopic('animal');
    }
    
    // 转换数据格式以匹配原有的模拟数据格式
    return wordsByCategory.map(word => ({
      word: word.english || '',
      pronunciation: word.pronunciation || '',
      definition: word.chinese || '',
      images: word.images || '' // 修改为正确的images字段名
    }));
  },

  // 生成错误选项
  generateIncorrectOptions: function(correctAnswer, allWords) {
    const incorrectOptions = [];
    const allDefinitions = allWords.map(word => word.definition);
    
    // 随机选择3个不同的错误选项
    while (incorrectOptions.length < 3) {
      const randomIndex = Math.floor(Math.random() * allDefinitions.length);
      const randomDefinition = allDefinitions[randomIndex];
      
      if (randomDefinition !== correctAnswer && !incorrectOptions.includes(randomDefinition)) {
        incorrectOptions.push(randomDefinition);
      }
    }
    
    return incorrectOptions;
  },

  // 选择答案
  selectOption: function(e) {
    // 已经选择了答案，不允许重复选择
    if (this.data.isOptionSelected) {
      return;
    }
    
    const optionIndex = e.currentTarget.dataset.index;
    const currentQuestion = this.data.currentQuestion;
    const isCorrect = optionIndex === currentQuestion.correctAnswerIndex;
    
    this.setData({
      selectedOption: optionIndex,
      isOptionSelected: true,
      isCorrect: isCorrect
    });
    
    // 播放音效
    audioUtils.playSound(isCorrect ? 'right' : 'wrong');
    
    // 计算得分和播放得分动画
    if (isCorrect) {
      this.calculateScore(isCorrect);
      this.showScoreAnimation();
    } else {
      this.calculateScore(isCorrect);
    }
    
    // 判断是否完成所有题目
    const isLastQuestion = this.data.currentQuestionIndex === this.data.totalQuestions - 1;
    this.setData({
      isLastQuestion: isLastQuestion
    });
    
    if (isLastQuestion) {
      setTimeout(() => {
        this.completeChallenge();
      }, 1500);
    }
  },
  
  // 计算得分
  calculateScore: function(isCorrect) {
    const scoreValue = isCorrect ? 10 : 0;
    
    this.setData({
      currentScore: this.data.currentScore + scoreValue
    });
    
    if (isCorrect) {
      this.setData({
        correctAnswers: this.data.correctAnswers + 1,
        coinsEarned: this.data.coinsEarned + this.data.coinsPerCorrect
      });
    }
  },
  
  // 显示得分变化动画
  showScoreAnimation: function() {
    this.setData({
      isScoreChanging: true
    });
    
    setTimeout(() => {
      this.setData({
        isScoreChanging: false
      });
    }, 1000);
  },

  // 进入下一题
  goToNextQuestion: function() {
    if (this.data.currentQuestionIndex >= this.data.totalQuestions - 1) {
      // 已经是最后一题
      this.completeChallenge();
      return;
    }
    
    const nextIndex = this.data.currentQuestionIndex + 1;
    const progress = Math.round((nextIndex / this.data.totalQuestions) * 100);
    
    this.setData({
      currentQuestionIndex: nextIndex,
      currentQuestion: this.data.questions[nextIndex],
      correctAnswerIndex: this.data.questions[nextIndex].correctAnswerIndex,
      selectedOption: -1,
      isOptionSelected: false,
      isCorrect: false,
      progressPercentage: progress
    });
  },

  // 显示提示
  showHint: function() {
    if (this.data.hintsUsed >= this.data.maxHints || this.data.isOptionSelected) {
      return;
    }
    
    // 增加使用的提示次数
    this.setData({
      hintsUsed: this.data.hintsUsed + 1
    });
    
    // 显示提示动画（闪烁正确答案选项）
    const correctIndex = this.data.correctAnswerIndex;
    this.setData({
      hintAnimation: correctIndex
    });
    
    // 3秒后停止提示动画
    setTimeout(() => {
      this.setData({
        hintAnimation: -1
      });
    }, 3000);
    
    wx.showToast({
      title: '已提示正确答案位置',
      icon: 'none'
    });
  },
  
  // 播放单词发音
  playWordPronunciation: function() {
    if (this.data.isOptionSelected) {
      return;
    }
    
    const currentWord = this.data.currentQuestion;
    
    if (this.audioManager) {
      try {
        // 获取美式发音URL (也可以使用'british'获取英式发音)
        const pronunciationType = 'american';
        let audioUrl = this.audioManager.getAudioUrl(currentWord, pronunciationType);
        
        // 现在直接传入单词对象，让audioManager内部处理音频URL获取
        this.audioManager.playPronunciation(currentWord, 1.0, pronunciationType)
          .catch(error => {
            console.error('播放发音失败:', error);
            // 错误已经在audioManager内部处理，这里可以省略重复的错误提示
          });
      } catch (error) {
          console.error('播放发音时出错:', error);
          // 主错误处理已在audioManager中实现
      }
    } else {
      wx.showToast({
        title: '发音功能暂不可用',
        icon: 'none'
      });
    }
  },

  // 播放音频题目
  playAudio: function() {
    // 直接调用playWordPronunciation函数来复用音频播放逻辑
    this.playWordPronunciation();
  },

  // 完成挑战
  completeChallenge: function() {
    // 计算最终结果
    const accuracy = Math.round((this.data.correctAnswers / this.data.totalQuestions) * 100);
    const isWin = this.data.currentScore >= this.data.passingScore;
    let finalCoins = this.data.coinsEarned;
    let resultMessage = '';
    
    // 胜利奖励
    if (isWin) {
      finalCoins += this.data.bonusForWin;
      
      if (accuracy >= 90) {
        resultMessage = '太棒了！你完全掌握了这个主题的单词！';
      } else if (accuracy >= 70) {
        resultMessage = '做得很好！继续保持！';
      } else {
        resultMessage = '恭喜通过！再接再厉！';
      }
    } else {
      resultMessage = '别灰心，再试一次吧！';
    }
    
    this.setData({
      isChallengeCompleted: true,
      isWin: isWin,
      finalScore: this.data.currentScore,
      finalCoins: finalCoins,
      accuracy: accuracy,
      resultMessage: resultMessage,
      progressPercentage: 100
    });
    
    // 保存挑战结果到本地存储
    this.saveChallengeResult();
  },

  // 保存挑战结果
  saveChallengeResult: function() {
    try {
      // 构建挑战记录
      const challengeRecord = {
        type: `主题挑战-${this.data.topicName}`,
        topic: this.data.topic,
        date: new Date().toISOString(),
        isWin: this.data.isWin,
        score: this.data.finalScore,
        duration: this.data.challengeDuration || 0
      };
      
      // 保存挑战记录
      challengeDataManager.addChallengeRecord(challengeRecord);
      
      // 更新魔法币
      if (this.data.finalCoins > 0) {
        this.magicCoinManager.addMagicCoins(this.data.finalCoins);
      }
      
      console.log('挑战结果保存成功');
    } catch (e) {
      console.error('保存挑战结果失败:', e);
    }
  },

  // 再玩一次
  playAgain: function() {
    this.initChallenge();
  },

  // 返回挑战主页
  backToChallenge: function() {
    wx.navigateBack();
  },

  // 选择其他主题
  chooseAnotherTopic: function() {
    wx.navigateTo({
      url: '/pages/challenge/challenge'
    });
  },

  // 分享挑战
  onShareAppMessage: function() {
    return {
      title: `我在${this.data.topicName}主题挑战中获得了${this.data.finalScore}分！快来挑战吧！`,
      path: `/pages/challenge/topic-challenge?topic=${this.data.topic}&topicName=${encodeURIComponent(this.data.topicName)}`,
      // imageUrl: '/images/book.png'
    };
  },
  
  // 分享到朋友圈
  onShareTimeline: function() {
    return {
      title: `我在${this.data.topicName}主题挑战中获得了${this.data.finalScore}分！快来挑战吧！`,
      query: `from=timeline&topic=${this.data.topic}&topicName=${encodeURIComponent(this.data.topicName)}`,
      // imageUrl: '/images/book.png'
    };
  }
});